/**
 * 
 */
package org.vectrics.recruiter.struts.cv;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionMessages;
import org.vectrics.cv.Language;
import org.vectrics.cv.Level;
import org.vectrics.cv.PersonLanguage;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;

/**
 * @author maguero
 * 
 * Clase que representa el Action para asignar un nuevo idioma.
 */
public class AddLanguageAction extends StudiesAction {

private transient static Logger log = Logger.getLogger(AddLanguageAction.class);
	
	private LanguageForm form;
	
	public LanguageForm getLanguageForm() {
		return form;
	}
	
	public void setForm(LanguageForm form) {
		this.form = form;
	}
	
	@Override
	protected String doExecute(VectricsActionData actionData)
			throws JspException {
		log.info("AddLanguageAction.doExecute() called");
		
		// Seteo el formulario 
		this.setForm((LanguageForm) actionData.getForm());
		Request request = actionData.getRequest();
		Long personId = null;
		if (request.getParameter("personId")!=null) {
			   personId = new Long(request.getParameter("personId"));
		}
		
		Long idLanguage = new Long(this.getLanguageForm().getLanguage());
		Long idLevel = new Long(this.getLanguageForm().getLanguageLevel());

		// obtenemos los idiomas ya cargados
		Collection<PersonLanguage> languages = CoreServiceLocator.getPersonService().findLanguagesByIdPerson(personId);
		
		boolean exist = false;
		for (Iterator iteratorLanguage = languages.iterator(); iteratorLanguage.hasNext();) {
			PersonLanguage personLanguage = (PersonLanguage) iteratorLanguage.next();
			if (personLanguage.getLanguage().getId().longValue() == idLanguage.longValue()) {
				exist = true;
				break;
			}
		}
		
		if (!exist) {
			// si el idioma no esta cargado lo persistimos
			CoreServiceLocator.getPersonService().addPersonLanguage(personId, idLanguage, idLevel);
		} else {
			// sino, mostramos advertencia de que ya existe
			actionData.addError(ActionMessages.GLOBAL_MESSAGE, "error.person.language.duplicated");
		}
		
		return super.doExecute(actionData);
	}
	
}
